const app = getApp();
const formatTime = date => {
    const year = date.getFullYear()
    const month = date.getMonth() + 1
    const day = date.getDate()
    const hour = date.getHours()
    const minute = date.getMinutes()
    const second = date.getSeconds()
    return [year, month, day].map(formatNumber).join('/') + ' ' + [hour, minute, second].map(formatNumber).join(':')
}

const formatNumber = n => {
    n = n.toString()
    return n[1] ? n : '0' + n
}

//获取当前日期，以“月日”连接
const formatDateCHWithoutYear = date => {
    const year = date.getFullYear()
    const month = formatNumber(date.getMonth() + 1)
    const day = formatNumber(date.getDate())
    return month + "月" + day + "日"
}

/**
 * 封封微信的的request
 */
function request(url, data = {}, method = "GET") {
    wx.showLoading({
        title: '加载中...',
    });
    return new Promise(function(resolve, reject) {
        wx.request({
            url: url,
            data: data,
            method: method,
            header: {
                'Content-Type': 'application/json',
                'openId': wx.getStorageSync('openid')
            },
            success: function(res) {
                wx.hideLoading();
                if (res.statusCode == 200) {
                    if (res.data.code == 401) {
                        var pages = getCurrentPages();
                        pages.pop().selectComponent('#login').openLoginModal();

                    } else {
                        resolve(res.data);
                    }
                } else {
                    wx.showToast({
                        title: res.errMsg, //提示的内容,
                        icon: "none", //图标,
                        //duration: 1500, //延迟时间,
                        mask: false, //显示透明蒙层，防止触摸穿透,
                    });
                    setTimeout(function() {
                        wx.hideToast();
                    }, 2000)
                }
            },
            fail: function(err) {
                console.log("failed");
                wx.hideLoading();
                wx.showToast({
                    title: "网络连接出错", //提示的内容,
                    icon: "none", //图标,
                    //duration: 1500, //延迟时间,
                    mask: false, //显示透明蒙层，防止触摸穿透,
                });
                setTimeout(function() {
                        wx.hideToast();
                    }, 2000)
                    //reject(err)
            }
        })
    });
}

function get(url, data = {}) {
    return request(url, data, 'GET')
}

function post(url, data = {}) {
    return request(url, data, 'POST')
}

/**
 * 检查微信会话是否过期
 */
function checkSession() {
    return new Promise(function(resolve, reject) {
        wx.checkSession({
            success: function() {
                resolve(true);
            },
            fail: function() {
                reject(false);
            }
        })
    });
}

/**
 * 调用微信登录
 */
function login() {
    return new Promise(function(resolve, reject) {
        wx.login({
            success: function(res) {
                if (res.code) {
                    resolve(res.code);
                } else {
                    reject(res);
                }
            },
            fail: function(err) {
                reject(err);
            }
        });
    });
}

function getUserInfo() {
    return new Promise(function(resolve, reject) {
        wx.getUserInfo({
            withCredentials: true,
            success: function(res) {
                if (res.detail.errMsg === 'getUserInfo:ok') {
                    resolve(res);
                } else {
                    reject(res)
                }
            },
            fail: function(err) {
                reject(err);
            }
        })
    });
}

function redirect(url) {

    //判断页面是否需要登录
    if (false) {
        wx.redirectTo({
            url: '/pages/auth/login/login'
        });
        return false;
    } else {
        wx.redirectTo({
            url: url
        });
    }
}

function showErrorToast(msg) {
    wx.showToast({
        title: msg,
        image: '/static/images/icon-error.png'
    })
}

function addDate(days) {
    if(days == undefined || days == '') {
        days = 1;
    }
    var date = new Date();
    date.setDate(date.getDate() + days);
    return date;
}


module.exports = {
    formatTime,
    formatNumber,
    request,
    get,
    post,
    redirect,
    showErrorToast,
    checkSession,
    login,
    getUserInfo,
    getStorageOpenId,
    getOpenid,
    formatDateCHWithoutYear,
    addDate
}



//----------------------------------------------用户是否登录 未登录跳转到登录页面 -------------------------


function getStorageOpenId() {
    const openId = wx.getStorageSync("openId");
    if (openId) {
        return openId;
    } else {
        return ''
    }
}




function getOpenid() {
    // wx.login({
    //   success: res => {
    //     if (res.code) {
    //       //发起网络请求
    //       wx.request({
    //         url: 'https://api.weixin.qq.com/sns/jscode2session',
    //         data: {
    //           "appid": "wx601ce71bde7b9add",
    //           "secret": "abed5421d88eb8236e933c6e42d5c14e",
    //           "js_code": res.code,
    //           "grant_type": "authorization_code"
    //         },
    //         success: function (data) {
    //           var openid = data.data.openid;
    //           wx.setStorageSync("openid", openid);
    //         }
    //       })
    //     } else {
    //       console.log('登录失败！' + res.errMsg)
    //     }

    //   },
    //   fail: () => {},
    //   complete: () => {}
    // });
}